<template>
  <div class="rule-sql-container">
    <!-- 查询SQL部分 -->
    <div class="query-section">
      <h3>SQL查询</h3>
      <div class="query-input-group">
        <el-input
          v-model="querySQL"
          type="textarea"
          :rows="3"
          placeholder="输入查询SQL语句..."
          class="query-textarea"
        />
        <div class="query-buttons">
          <el-button
            type="primary"
            @click="executeQuery"
            :loading="queryLoading"
          >
            <el-icon><Search /></el-icon>
            执行查询
          </el-button>
        </div>
      </div>

      <!-- 查询结果显示 -->
      <div
        v-if="queryResult.data && queryResult.data.length > 0"
        class="query-result"
      >
        <h4>查询结果 (共 {{ queryResult.total }} 条记录)</h4>
        <el-table
          :data="queryResult.data"
          border
          stripe
          style="width: 100%"
          max-height="400"
        >
          <el-table-column
            v-for="column in queryResultColumns"
            :key="column"
            :prop="column"
            :label="column"
            :width="getColumnWidth(column)"
            show-overflow-tooltip
          />
        </el-table>
      </div>

      <!-- 查询错误信息 -->
      <div v-if="queryError" class="error-message">
        <el-alert :title="queryError" type="error" show-icon />
      </div>
    </div>

    <el-divider />

    <!-- SQL执行部分 -->
    <div class="sql-execution-section">
      <h3>SQL执行</h3>
      <div
        v-for="(pathItem, pathIndex) in localSqlData"
        :key="pathIndex"
        class="path-section"
      >
        <div class="path-header sticky-header" @click="togglePath(pathIndex)">
          <div class="header-left">
            <el-icon class="expand-icon">
              <ArrowDown v-if="pathItem.expanded" />
              <ArrowRight v-else />
            </el-icon>
            <el-tag type="primary" size="large" class="path-tag">
              {{ pathItem.path }}
            </el-tag>
            <el-divider direction="vertical" />
            <span class="sql-count">{{ pathItem.sqlList.length }} 条SQL</span>
          </div>
          <div class="header-actions">
            <el-button
              type="text"
              size="small"
              @click.stop="executeAllSQL(pathIndex)"
              class="execute-all-btn"
              :loading="isExecutingAll(pathIndex)"
            >
              <el-icon><VideoPlay /></el-icon>
              从头执行所有
            </el-button>
            <!-- 进度显示 -->
            <div v-if="isExecutingAll(pathIndex)" class="execution-progress">
              <el-progress
                :percentage="getExecutionProgress(pathIndex)"
                :stroke-width="4"
                :show-text="false"
                color="#67c23a"
              />
              <span class="progress-text">
                {{ getProgressText(pathIndex) }}
              </span>
            </div>
            <el-divider direction="vertical" />
            <el-button
              type="text"
              size="small"
              @click.stop="togglePath(pathIndex)"
              class="expand-btn"
            >
              <el-icon>
                <ArrowDown v-if="pathItem.expanded" />
                <ArrowRight v-else />
              </el-icon>
              {{ pathItem.expanded ? "收起" : "展开" }}
            </el-button>
          </div>
        </div>

        <div v-show="pathItem.expanded" class="sql-list">
          <div
            v-for="(sql, sqlIndex) in pathItem.sqlList"
            :key="sqlIndex"
            :data-path="pathIndex"
            :data-sql="sqlIndex"
            :class="[
              'sql-item',
              {
                'sql-item-executing': isCurrentExecutingSQL(
                  pathIndex,
                  sqlIndex
                ),
              },
            ]"
          >
            <div class="sql-header">
              <span class="sql-index">SQL {{ sqlIndex + 1 }}</span>
              <div class="sql-buttons">
                <el-button
                  size="small"
                  type="primary"
                  @click="executeSingleSQL(pathIndex, sqlIndex)"
                  :loading="isExecuting(pathIndex, sqlIndex)"
                >
                  <el-icon><VideoPlay /></el-icon>
                  执行
                </el-button>
                <el-button
                  size="small"
                  type="success"
                  @click="executeFromStart(pathIndex, sqlIndex)"
                  :loading="isExecutingFromStart(pathIndex, sqlIndex)"
                >
                  <el-icon><CaretRight /></el-icon>
                  从头执行到此
                </el-button>
                <el-button
                  size="small"
                  type="info"
                  @click="toggleSQLExpand(pathIndex, sqlIndex)"
                >
                  <el-icon>
                    <ArrowUp v-if="sql.expanded" />
                    <ArrowDown v-else />
                  </el-icon>
                  {{ sql.expanded ? "收起" : "展开" }}
                </el-button>
              </div>
            </div>

            <div class="sql-content">
              <el-input
                v-model="sql.content"
                type="textarea"
                :rows="sql.expanded ? 8 : 3"
                class="sql-textarea"
                placeholder="SQL语句..."
              />
            </div>

            <!-- 执行结果显示 -->
            <div v-if="sql.result" class="sql-result">
              <div v-if="sql.result.mark === 'OK'" class="success-result">
                <p><strong>执行成功!</strong></p>
                <p>
                  影响行数: <span>{{ sql.result.data.rowCount }}</span>
                </p>
                <div class="table-counts">
                  <el-button
                    v-for="(count, tableName) in sql.result.data.tableCounts"
                    :key="tableName"
                    :type="count > 0 ? 'success' : 'info'" size="small" class="table-count-tag"
                    @click="openResultDialog(tableName)"
                  >
                    {{ tableName }}: {{ count }} |
                  </el-button>
                </div>
              </div>
              <div v-else class="error-result">
                <el-alert :title="sql.result.msg" type="error" show-icon />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 结果对话框 -->
    <rule-sql-result
      v-model="resultRows"
      v-model:visible="resultDialogVisible"
      :focus-tbl-name="focusTblName"
      @refresh="handleRefresh"
    />
  </div>
</template>

<script setup>
/* eslint-env es6 */
/* global defineProps */
import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";
import {
  Search,
  VideoPlay,
  CaretRight,
  ArrowDown,
  ArrowRight,
  ArrowUp,
} from "@element-plus/icons-vue";

// Props
const props = defineProps({
  sqlData: {
    type: Array,
    default: () => [],
  },
});

// 响应式数据
const querySQL = ref("");
const queryLoading = ref(false);
const queryResult = ref({ data: [], total: 0 });
const queryError = ref("");
const executingStatus = ref({}); // 记录正在执行的SQL状态
const executingFromStartStatus = ref({}); // 记录从头执行的状态
const executingAllStatus = ref({}); // 记录批量执行状态
const executionProgress = ref({}); // 记录批量执行进度 { pathIndex: { current: 0, total: 0, currentSQLIndex: -1 } }

// 处理sqlData，添加展开状态和结果状态
const localSqlData = ref([]);

// 监听props变化，初始化本地数据
watch(
  () => props.sqlData,
  (newData) => {
    localSqlData.value = newData.map((pathItem) => ({
      ...pathItem,
      expanded: true, // 默认展开
      sqlList: pathItem.sqlList.map((sql) => ({
        content: sql,
        expanded: false, // 默认收起
        result: null,
      })),
    }));
  },
  { immediate: true, deep: true }
);

// 计算查询结果的列
const queryResultColumns = computed(() => {
  if (!queryResult.value.data || queryResult.value.data.length === 0) {
    return [];
  }

  // 获取所有可能的列名
  const allColumns = new Set();
  queryResult.value.data.forEach((row) => {
    Object.keys(row).forEach((key) => {
      allColumns.add(key);
    });
  });

  // 过滤掉全部为空值的列
  const validColumns = Array.from(allColumns).filter((column) => {
    return queryResult.value.data.some((row) => {
      const value = row[column];
      return value !== null && value !== undefined && value !== "";
    });
  });

  return validColumns;
});

// 切换path展开状态
const togglePath = (pathIndex) => {
  localSqlData.value[pathIndex].expanded =
    !localSqlData.value[pathIndex].expanded;
};

// 切换SQL展开状态
const toggleSQLExpand = (pathIndex, sqlIndex) => {
  localSqlData.value[pathIndex].sqlList[sqlIndex].expanded =
    !localSqlData.value[pathIndex].sqlList[sqlIndex].expanded;
};

// 检查是否正在执行单个SQL
const isExecuting = (pathIndex, sqlIndex) => {
  return executingStatus.value[`${pathIndex}-${sqlIndex}`] || false;
};

// 检查是否正在从头执行
const isExecutingFromStart = (pathIndex, sqlIndex) => {
  return executingFromStartStatus.value[`${pathIndex}-${sqlIndex}`] || false;
};

// 检查是否正在执行所有SQL
const isExecutingAll = (pathIndex) => {
  return executingAllStatus.value[pathIndex] || false;
};

// 获取执行进度百分比
const getExecutionProgress = (pathIndex) => {
  const progress = executionProgress.value[pathIndex];
  if (!progress || progress.total === 0) return 0;
  return Math.round((progress.current / progress.total) * 100);
};

// 获取进度文本
const getProgressText = (pathIndex) => {
  const progress = executionProgress.value[pathIndex];
  if (!progress) return "";
  return `${progress.current}/${progress.total}`;
};

// 检查是否为当前正在执行的SQL
const isCurrentExecutingSQL = (pathIndex, sqlIndex) => {
  const progress = executionProgress.value[pathIndex];
  return progress && progress.currentSQLIndex === sqlIndex;
};

// 执行查询SQL
const executeQuery = async () => {
  if (!querySQL.value.trim()) {
    ElMessage.warning("请输入查询SQL");
    return;
  }

  queryLoading.value = true;
  queryError.value = "";

  try {
    const response = await axios.post("/api/rule_apply/query_sql_exec", {
      sql: querySQL.value,
    });

    const result = response.data;

    if (result.mark === "OK") {
      queryResult.value = result;
      ElMessage.success("查询成功");
    } else {
      queryError.value = result.msg;
      ElMessage.error("查询失败: " + result.msg);
    }
  } catch (error) {
    const errorMsg = error.response?.data?.msg || error.message || "网络错误";
    queryError.value = "网络错误: " + errorMsg;
    ElMessage.error("查询失败: " + errorMsg);
  } finally {
    queryLoading.value = false;
  }
};

// 执行单个SQL
const executeSingleSQL = async (pathIndex, sqlIndex) => {
  const sql = localSqlData.value[pathIndex].sqlList[sqlIndex];
  if (!sql.content.trim()) {
    ElMessage.warning("SQL内容不能为空");
    return;
  }

  const key = `${pathIndex}-${sqlIndex}`;
  executingStatus.value[key] = true;

  try {
    const response = await axios.post("/api/rule_apply/exec_sql", {
      sql: sql.content,
    });

    const result = response.data;
    sql.result = result;

    if (result.mark === "OK") {
      ElMessage.success("SQL执行成功");
    } else {
      ElMessage.error("SQL执行失败: " + result.msg);
    }
  } catch (error) {
    const errorMsg = error.response?.data?.msg || error.message || "网络错误";
    sql.result = {
      mark: "ERR",
      msg: "网络错误: " + errorMsg,
    };
    ElMessage.error("执行失败: " + errorMsg);
  } finally {
    executingStatus.value[key] = false;
  }
};

// 从头执行到指定SQL
const executeFromStart = async (pathIndex, sqlIndex) => {
  const key = `${pathIndex}-${sqlIndex}`;
  executingFromStartStatus.value[key] = true;

  try {
    // 依次执行从0到sqlIndex的所有SQL
    for (let i = 0; i <= sqlIndex; i++) {
      const sql = localSqlData.value[pathIndex].sqlList[i];
      if (sql.content.trim()) {
        await executeSQLItem(sql);
      }
    }
    ElMessage.success("批量执行完成");
  } catch (error) {
    ElMessage.error("批量执行失败: " + error.message);
  } finally {
    executingFromStartStatus.value[key] = false;
  }
};

// 执行单个SQL项的辅助函数
const executeSQLItem = async (sqlItem) => {
  const response = await axios.post("/api/rule_apply/exec_sql", {
    sql: sqlItem.content,
  });

  const result = response.data;
  sqlItem.result = result;

  if (result.mark !== "OK") {
    throw new Error(result.msg);
  }
};

// 执行所有SQL
const executeAllSQL = async (pathIndex) => {
  executingAllStatus.value[pathIndex] = true;

  try {
    const pathItem = localSqlData.value[pathIndex];
    const validSQLs = pathItem.sqlList.filter((sql) => sql.content.trim());
    const totalCount = validSQLs.length;
    let executedCount = 0;

    // 初始化进度
    executionProgress.value[pathIndex] = {
      current: 0,
      total: totalCount,
      currentSQLIndex: -1,
    };

    // 展开path
    pathItem.expanded = true;

    // 依次执行所有SQL
    for (let i = 0; i < pathItem.sqlList.length; i++) {
      const sql = pathItem.sqlList[i];
      if (sql.content.trim()) {
        // 更新当前执行的SQL索引
        executionProgress.value[pathIndex].currentSQLIndex = i;

        // 自动跳转到当前执行的SQL
        await scrollToCurrentSQL(pathIndex, i);

        // 执行SQL
        await executeSQLItem(sql);
        executedCount++;

        // 更新进度
        executionProgress.value[pathIndex].current = executedCount;

        // 展开刚执行的SQL以显示结果
        sql.expanded = true;

        // 短暂延迟，让用户看到进度
        await new Promise((resolve) => setTimeout(resolve, 200));
      }
    }

    ElMessage.success(
      `批量执行完成，共执行 ${executedCount}/${totalCount} 条SQL`
    );

    // 跳转到最后一个SQL
    await scrollToLastSQL(pathIndex);
  } catch (error) {
    ElMessage.error("批量执行失败: " + error.message);
  } finally {
    executingAllStatus.value[pathIndex] = false;
    // 清除进度信息
    delete executionProgress.value[pathIndex];
  }
};

// 滚动到当前执行的SQL
const scrollToCurrentSQL = async (pathIndex, sqlIndex) => {
  await new Promise((resolve) => setTimeout(resolve, 100)); // 等待DOM更新

  const currentSqlElement = document.querySelector(
    `[data-path="${pathIndex}"][data-sql="${sqlIndex}"]`
  );

  if (currentSqlElement) {
    currentSqlElement.scrollIntoView({
      behavior: "smooth",
      block: "center",
    });
  }
};

// 滚动到最后一个SQL
const scrollToLastSQL = async (pathIndex) => {
  await new Promise((resolve) => setTimeout(resolve, 100)); // 等待DOM更新

  const pathItem = localSqlData.value[pathIndex];
  const lastSqlIndex = pathItem.sqlList.length - 1;

  const lastSqlElement = document.querySelector(
    `[data-path="${pathIndex}"][data-sql="${lastSqlIndex}"]`
  );

  if (lastSqlElement) {
    lastSqlElement.scrollIntoView({
      behavior: "smooth",
      block: "center",
    });
  }
};

// 计算列宽度
const getColumnWidth = (column) => {
  const baseWidth = 120;
  const maxWidth = 300;
  const calculatedWidth = Math.min(
    maxWidth,
    Math.max(baseWidth, column.length * 8 + 40)
  );
  return calculatedWidth;
};

// 引入 ruleSqlResult 组件
import RuleSqlResult from "./ruleSqlResult.vue";
const resultRows = ref([]);
const resultDialogVisible = ref(false);
const focusTblName = ref("");
const handleRefresh = (rows) => {
  resultRows.value = Array.isArray(rows) ? rows : [];
};

const openResultDialog = (tableName) => {
  focusTblName.value = tableName;
  resultDialogVisible.value = true;
  console.log(resultDialogVisible.value, focusTblName.value)
};
</script>

<style scoped>
.rule-sql-container {
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  min-height: 100vh;
  position: relative;
}

.query-section {
  margin-bottom: 20px;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.query-section h3 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.query-input-group {
  margin-bottom: 16px;
}

.query-textarea {
  margin-bottom: 12px;
}

.query-buttons {
  display: flex;
  gap: 8px;
}

.query-result {
  margin-top: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.error-message {
  margin-top: 16px;
}

.sql-execution-section {
  margin-top: 20px;
}

.sql-execution-section > h3 {
  margin: 0 0 20px 0;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.path-section {
  margin-bottom: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: visible; /* 改为visible确保sticky能正常工作 */
  position: relative;
}

.path-header {
  padding: 10px 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  cursor: pointer;
  transition: all 0.2s ease;
  min-height: 40px;
}

.sticky-header {
  position: sticky;
  top: 10px;
  z-index: 100;
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.path-header:hover {
  background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.expand-icon {
  font-size: 14px;
}

.path-tag {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  font-weight: 600;
  font-size: 12px;
  padding: 4px 8px;
}

.sql-count {
  font-size: 12px;
  opacity: 0.9;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 6px;
}

.execution-progress {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: 8px;
  padding: 4px 8px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  min-width: 120px;
}

.execution-progress .el-progress {
  flex: 1;
}

.progress-text {
  color: white;
  font-size: 11px;
  font-weight: 500;
  white-space: nowrap;
}

.expand-btn {
  color: white !important;
  border-color: rgba(255, 255, 255, 0.3);
  transition: all 0.2s ease;
  padding: 4px 8px;
  font-size: 12px;
  height: 28px;
}

.expand-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.execute-all-btn {
  color: #67c23a !important;
  border-color: rgba(103, 194, 58, 0.5);
  background: rgba(103, 194, 58, 0.1);
  transition: all 0.2s ease;
  padding: 4px 8px;
  font-size: 12px;
  height: 28px;
}

.execute-all-btn:hover {
  background: rgba(103, 194, 58, 0.2);
  color: #67c23a !important;
}

.sql-list {
  padding: 12px;
  background: #f8f9fa;
}

.sql-item {
  margin-bottom: 16px;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.sql-item:last-child {
  margin-bottom: 0;
}

.sql-item-executing {
  border-color: #67c23a !important;
  box-shadow: 0 0 15px rgba(103, 194, 58, 0.3) !important;
  background: linear-gradient(145deg, #f0f9ff 0%, #ecfdf5 100%) !important;
  transform: scale(1.02);
}

.sql-item-executing .sql-header {
  background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%) !important;
  border-left-color: #67c23a !important;
}

.sql-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 8px 12px;
  background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
  border-radius: 4px;
  border-left: 3px solid #667eea;
}

.sql-index {
  font-weight: 600;
  color: #667eea;
  font-size: 14px;
}

.sql-buttons {
  display: flex;
  gap: 6px;
}

.sql-content {
  margin-bottom: 10px;
}

.sql-textarea {
  font-family: "Consolas", "Monaco", "Courier New", monospace;
  font-size: 13px;
}

.sql-result {
  margin-top: 10px;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
}

.success-result {
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border: 1px solid #bae6fd;
  color: #0f172a;
}

.success-result p {
  margin: 0 0 6px 0;
  font-size: 13px;
}

.table-counts {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 6px;
}

.table-count-tag {
  margin: 0;
  font-size: 11px;
}

.error-result {
  background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
  border: 1px solid #fecaca;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .rule-sql-container {
    padding: 10px;
  }

  .path-header {
    padding: 8px 12px;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    min-height: auto;
  }

  .sticky-header {
    top: 5px;
  }

  .header-left {
    width: 100%;
    justify-content: space-between;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .sql-buttons {
    flex-direction: column;
  }

  .sql-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .query-buttons {
    flex-direction: column;
  }

  .sql-list {
    padding: 8px;
  }

  .sql-item {
    padding: 8px;
  }
}

/* 分割线样式 */
:deep(.el-divider--vertical) {
  margin: 0 8px;
  background-color: rgba(255, 255, 255, 0.3);
}
</style>
